/*
 * ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is
 *
 * java-concurrency-presentation:
 * concurrency presentation tutorial.
 *
 * The Initial Developer of the Original Code is
 * Marco Antonio Villalobos, Jr.
 * Portions created by the Initial Developer are Copyright (C) 2010
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s): None.
 *
 * ***** END LICENSE BLOCK *****
 */

package presentation.concurrency.slides;

import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

/**
 * Provides an example on how to use a thread pool.
 */
public class Pool<T> {

    /** place holder that makes psuedo-code prettier. */
    private final T r = null;                               //this variable is here just to make psuedo-code prettier

    /**
     * Provides an example on how to use a thread pool.
     */
    public void main() {
        final int POOL_SIZE = 32;
        ExecutorService pool = Executors.newFixedThreadPool(POOL_SIZE);

        Future<T> future = pool.submit(new Callable<T>() {
            public T call() throws Exception {
                return r;  // ... calculate result
            }
        });

        try {
            T f = future.get();
        } catch (InterruptedException e) {
            // allow for exit
        } catch (ExecutionException e) {
            // ... handle exception that happened in call()
        }

        pool.shutdown();
        try {
            pool.awaitTermination(Integer.MAX_VALUE, TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            // allow for exit
        }
    }
}